package com.itboye.eweilisten.me.timu;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.me.timu.adapter.ZongHeAdapter;
import com.itboye.eweilisten.model.TIbean;
import com.itboye.eweilisten.model.TIbeanTwo;
import com.itboye.eweilisten.model.TiXingBean;
import com.itboye.eweilisten.model.YesCuoBean;
import com.itboye.eweilisten.presenter.TiMuPresenter;
import com.itboye.eweilisten.util.MyDownLoaderTask;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.logincontroller.UnLoginState;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.SPUtils;
import com.itboye.eweilisten.volley.ResultEntity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.PriorityQueue;

import static com.itboye.eweilisten.util.logincontroller.LoginController.setLoginState;

/**
 * 综合题
 */
public class ZongHeActivity extends BaseActivity implements Observer {
    TextView tvTitle;
    ImageView back;
    TextView zuoti_title, zuoti_title01;
    TextView zuoti_zidong;
    TextView zuoti_shoudong;

    ZongHeAdapter adapter;
    RecyclerView recyclerView;
    TiMuPresenter tiMuPresenter;
    TiXingBean bean;
    List<TiXingBean.ListInfo> beanList = new ArrayList<>();
    List<TIbeanTwo> beanTi = new ArrayList<>();

    ArrayList<ArrayList<String>> questions = new ArrayList<ArrayList<String>>();//内容
    ArrayList<TIbean.Options> answers = new ArrayList<TIbean.Options>();//答案前缀
    ArrayList<String> answerss = new ArrayList<String>();//答案内容

    ArrayList<String> answers_nei;//子类答案内容
    ArrayList<TIbean.Options> answers_qian;//子类答案前缀
    List<TIbean.Clild> cc = new ArrayList<TIbean.Clild>();

    ArrayList<String> que = new ArrayList<String>();//用来存6227类型的1.2.3.4

    String type;

    static MediaPlayer player;

    String uid;
    String sid;

    String tijiaoTime;

    TestTask testTask;
    CountDownTimer cdt;

    private boolean isShowkaishiWindow;
    int[] numberMP3 = {R.raw.number1, R.raw.number2, R.raw.number3, R.raw.number4, R.raw.number5,
            R.raw.number6, R.raw.number7, R.raw.number8, R.raw.number9, R.raw.number10,
            R.raw.number11, R.raw.number12, R.raw.number13, R.raw.number14, R.raw.number15,
            R.raw.number16, R.raw.number17,R.raw.number18,R.raw.number19,R.raw.number20};


    public String ROOT_DIR;//创建保存的路径

    public ProgressDialog loadingDialog;

    List<String> urlsss=new ArrayList<>();//存放mp3的播放地址，下载用
    List<String> namess=new ArrayList<>();//存放mp3的文件名，下载用
    List<String> wenjian_name=new ArrayList<>();//本地存放mp3的文件名，下载用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zong_he);

        tvTitle.setText("微测试");
        bean = new TiXingBean();
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tiMuPresenter = new TiMuPresenter(this);
        uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        type = getIntent().getStringExtra("type");
        showProgressDialog("加载题目中,请稍候", true);
        sid = (String) SPUtils.get(MyApplication.instance, null, Const.S_ID, "");
        Log.d("=====uid===",uid+"type=="+type+"sid=="+sid);
        tiMuPresenter.onXiangQing(uid, type, sid);


        ROOT_DIR ="/data/data/"+ this.getPackageName() + "/cache/yinyue";
        mopo();

        IntentFilter intentFilter=new IntentFilter("down_ok");
        registerReceiver(receiver,intentFilter);
    }
    BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            kaishiWindow();
        }
    };


    /**
     * 下载音频
     * @param list
     */
    private void downLoad(List<TiXingBean.ListInfo> list) {
        Log.d("===beanList==",list.toString());
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).getAudio_path().equals("")){
                urlsss.add(list.get(i).getAudio_path());
            }
            if (!list.get(i).getAudio_id().equals("")){
                namess.add(list.get(i).getAudio_id()+".mp3");
            }
        }
        File path = new File(ROOT_DIR);

        // 判断SD卡是否存在，并且是否具有读写权限
        if (Environment.getExternalStorageState().
                equals(Environment.MEDIA_MOUNTED)) {
            File[] files = path.listFiles();// 读取文件夹下文件
            wenjian_name=getFileName(files);
        }
        Boolean bo=false;

        for (int i = 0; i < namess.size(); i++) {   //循环遍历  如果本地有相同音频ID的Mp3,则不用下载

            for (int i1 = 0; i1 < wenjian_name.size(); i1++) {
                if (namess.get(i).equals(wenjian_name.get(i1))){

                   bo=true;
                    System.out.println("AAAAAAAAAAAAAAAAA正确:下标    "+i1+"     对错"+bo+"");
                    if (namess.size()-1==i){
                        break;
                    }else{
                        continue;
                    }
                }else{
                    System.out.println("AAAAAAAAAAAAAAAAA错误:下标    "+i1+"     对错"+bo+"");
                    bo=false;
                    break;
                }
            }

        }
        Log.d("====bo===",bo+"");
        if (bo==false){
            if (urlsss.size()>0){
                loadingDialog = new ProgressDialog(this);
                loadingDialog.setTitle("正在下载音频，请稍候...");
                loadingDialog.setMax(urlsss.size());
                loadingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                for (int i = 0; i < urlsss.size(); i++) {
                    MyDownLoaderTask task = new MyDownLoaderTask(this,loadingDialog, ROOT_DIR,urlsss.get(i), namess.get(i),i,urlsss.size());
                    task.execute();
                }
            }else{
                kaishiWindow();
            }
        }else{
            kaishiWindow();
        }


    }

    /**
     * 读取指定目录下的所文件名
     * @param files
     * @return
     */
    private List<String> getFileName(File[] files) {
        List<String>  lists=new ArrayList<>();
        String str = "";
        if (files != null) {    // 先判断目录是否为空，否则会报空指针
            for (File file : files) {
                if (file.isDirectory()){//检查此路径名的文件是否是一个目录(文件夹)
                    Log.i("zeng", "若是文件目录。继续读1"+file.getName().toString()+file.getPath().toString());
                    getFileName(file.listFiles());
                    Log.i("zeng", "若是文件目录。继续读2"+file.getName().toString()+ file.getPath().toString());
                } else {
                    String fileName = file.getName();
                    if (fileName.endsWith(".mp3")) {
                        lists.add(fileName);
                    }
                }
            }
        }
        return lists;
    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                showPopupWindow();
                break;
            case R.id.zuoti_shoudong://手动提交
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setTitle("手动提交");
                dialog.setMessage("您确定要提交答案吗");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (testTask != null) {
                            testTask.onCancelled();
                        }
                        submitAnswers();
                        finish();
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.create().show();

                break;
        }
    }

    private void submitAnswers() {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < beanTi.size(); i++) {
            if (beanTi.get(i).getAnwser_true().size() != 0) {
                sb.append(beanTi.get(i).getId() + ":" + beanTi.get(i).getXuan() + ",");
            }
            if (beanTi.get(i).getClild() != null) {
                for (int j = 0; j < beanTi.get(i).getClild().size(); j++) {
                    int s = beanTi.get(i).getClild().get(j).getXuan();
                    sb.append(beanTi.get(i).getClild().get(j).getId() + ":" + beanTi.get(i).getClild().get(j).getXuan() + ",");
                }
            }
        }
//                System.out.println(sb.toString() + "提交答案");
//                MAlert.alert(sb.substring(0, sb.length() - 1).toString());

        if (sb.length() > 0) {
            showProgressDialog("正在提交,请稍后...", true);
            tiMuPresenter.onTiJiao(uid, type, tijiaoTime, sb.substring(0, sb.length() - 1).toString());
        } else {
            MAlert.alert("答案有误");
        }
    }

    /**
     * 开始
     */
    private void kaishiWindow() {

        final View contentView = LayoutInflater.from(ZongHeActivity.this).inflate(
                R.layout.popwindow_start, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setAnimationStyle(R.style.popupwindow_anim_style);
        TextView cancel, sure;
        cancel = (TextView) contentView.findViewById(R.id.cancel);
        sure = (TextView) contentView.findViewById(R.id.sure);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                if (testTask != null) {
                    testTask.onCancelled();
                    testTask = null;
                }
                finish();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                recyclerView.setVisibility(View.VISIBLE);
                cdt = new CountDownTimer(Integer.parseInt(bean.getTime_limit() + "") * 1000, 1000) {
                    //                    CountDownTimer cdt = new CountDownTimer(5000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        zuoti_zidong.setText("自动提交：" + millisUntilFinished / 1000 + "″");

                        long time = millisUntilFinished / 1000;
                        tijiaoTime = String.valueOf(Long.parseLong(bean.getTime_limit()) - time);
                    }

                    @Override
                    public void onFinish() {
                        if (testTask != null) {
                            //自动提交操作
                            if (testTask != null) {
                                testTask.onCancelled();
                            }
                            submitAnswers();
                            finish();
                        }

                    }
                };
                cdt.start();
                if (beanList.size() > 0) {
                    testTask = new TestTask();
                    testTask.execute();
                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("mengdd", "onTouch : ");
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
    }

    /**
     * 退出
     */
    private void showPopupWindow() {
        final View contentView = LayoutInflater.from(ZongHeActivity.this).inflate(
                R.layout.popwindow_back, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popupwindow_anim_style);
        TextView cancel, sure;
        cancel = (TextView) contentView.findViewById(R.id.cancel);
        sure = (TextView) contentView.findViewById(R.id.sure);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                if (testTask != null) {
                    testTask.onCancelled();
                }
                finish();
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("mengdd", "onTouch : ");
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    class TestTask extends AsyncTask<String, Integer, String> {

        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(beanList.size());


        @Override
        protected void onProgressUpdate(Integer... values) {

            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(player!=null){
                if (player.isPlaying()) {
                    player.stop();
                }
                player.release();
                player = null;
            }
            if (queue != null) {
                queue.clear();
                queue = null;
            }
            if (cdt != null) {
                cdt = null;
            }
        }

        @Override
        protected String doInBackground(String... strings) {
            Boolean isPlayNumber = bean.getIs_tip().equals("0");//本地是否不播放题号

            try {
                for (int i = 0; i < beanList.size(); i++) {
                    if (queue != null) {
                        synchronized (queue) {
                            if(beanList.get(i).getAudio_path().equals("")){
                                break;
                            }

                            if (player == null) {
                                Log.d("palyer==","isnull");
                                if (!isPlayNumber) {
                                    player = MediaPlayer.create(ZongHeActivity.this, numberMP3[i]);
                                    player.start();
                                    queue.wait(2300);
                                    queue.notify();
                                }
                                File file = new File(ROOT_DIR+"/"+namess.get(i));

                                if(file.exists()){
                                    try {
                                        player = new MediaPlayer();
                                        player.setDataSource(ROOT_DIR+"/"+namess.get(i));//设置播放的数据源。
                                        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                        player.prepare();//准备开始播放 播放的逻辑是c代码在新的线程里面执行。
                                        player.start();
                                        queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                        queue.notify();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        MAlert.alert("播放失败");
                                        player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                        player.start();
                                        queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                        queue.notify();
                                    }
                                }else{
                                    MAlert.alert("文件不存在，请检查文件的路径");
                                    player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                    player.start();
                                    queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                    queue.notify();
                                }


                            } else {
                                if (player.isPlaying()) {
                                    Log.d("===isPlaying===","yes");
                                     player.stop();
                                     player.reset();
                                    if (!isPlayNumber) {
                                        player = MediaPlayer.create(ZongHeActivity.this, numberMP3[i]);
                                        player.start();
                                        queue.wait(2300);
                                        queue.notify();
                                    }
                                    File file = new File(ROOT_DIR+"/"+namess.get(i));

                                    if(file.exists()){
                                        Log.d("=====exists==yes==",Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000+"");
                                        try {
                                            player = new MediaPlayer();
                                            player.setDataSource(ROOT_DIR+"/"+namess.get(i));//设置播放的数据源。
                                            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                            player.prepare();//准备开始播放 播放的逻辑是c代码在新的线程里面执行。
                                            player.start();
                                            queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                            queue.notify();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            MAlert.alert("播放失败");
                                            player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                            player.start();
                                            queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                            queue.notify();

                                        }
                                    }else{
                                        player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                        Log.d("=====noexists==yes==",Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000+"");
                                        player.start();
                                        queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                        queue.notify();
                                    }

                                } else {
                                    Log.d("===isPlaying===","no");
                                    if (!isPlayNumber) {
                                        player = MediaPlayer.create(ZongHeActivity.this, numberMP3[i]);
                                        player.start();
                                        queue.wait(2300);
                                        queue.notify();
                                    }
                                    File file = new File(ROOT_DIR+"/"+namess.get(i));

                                    if(file.exists()){
                                        player.reset();
                                        Log.d("====exists==no===",Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000+"");
                                        try {
                                            Log.d("====exists==no===","try==yes");
                                            player = new MediaPlayer();
                                            player.setDataSource(ROOT_DIR+"/"+namess.get(i));//设置播放的数据源。
                                            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                                            player.prepare();//准备开始播放 播放的逻辑是c代码在新的线程里面执行。
                                            player.start();
                                            queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                            queue.notify();
                                        } catch (Exception e) {
                                            Log.d("====exists==no===","try==no");
                                            e.printStackTrace();
                                            MAlert.alert("播放失败");
                                            player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                            player.start();
                                            queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                            queue.notify();

                                        }
                                    }else{
                                        player.reset();
                                        player = MediaPlayer.create(ZongHeActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                                        Log.d("=====noexists==no==",Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000+"");
                                        player.start();
                                        queue.wait(Integer.valueOf(beanList.get(i).getAudio_duration()) * 1000 + 1000);
                                        player.stop();
                                        queue.notify();
                                        player.reset();

                                    }
                                }
                            }
                            player.reset();
                            queue.poll();
                        }

                    }
                }
            } catch (Exception e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        AudioManager am=(AudioManager)getSystemService(Service.AUDIO_SERVICE);
        switch(keyCode){
            case KeyEvent.KEYCODE_VOLUME_UP:
                am.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);
                am.adjustStreamVolume(AudioManager.STREAM_DTMF,AudioManager.ADJUST_RAISE,0);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                am.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);
                am.adjustStreamVolume(AudioManager.STREAM_DTMF,AudioManager.ADJUST_RAISE,0);
                break;
            case  KeyEvent.KEYCODE_BACK:
                showPopupWindow();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void update(Observable observable, Object o) {
        ResultEntity entity = handlerError(o);
        if (entity != null) {
            if (!entity.getCode().equals("0")) {
                if (entity.getCode().equals("1111")) {//被挤掉
                    MAlert.alert(entity.getMsg());
                    setLoginState(new UnLoginState());//设置未登录状态
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    this.finish();
                    return;
                }
            }
            if (entity.getEventType() == tiMuPresenter.zuoti_xq_success) {
                bean = (TiXingBean) entity.getData();

                zuoti_title.setText(bean.getName());
                zuoti_title01.setText(bean.getParent_name());

                List<TiXingBean.ListInfo> list = new ArrayList<TiXingBean.ListInfo>();
                list.addAll(bean.getList());

               // beanList = list;
                beanList.clear();
                beanList.addAll(list);

                for (int i = 0; i < list.size(); i++) {
                    questions = new ArrayList<ArrayList<String>>();
                    answers = new ArrayList<>();
                    answerss = new ArrayList<>();
                    TIbeanTwo b = new TIbeanTwo();

                    int index = 0;
                    if (list.get(i).getDt_type().equals("6227")) {//注：6227类型空格填1.2.3.4 ,所以额外添加了一个不一样的
                        for (int j = 0; j < list.get(i).getContent().get(0).size(); j++) {
                            if ("con".equals(list.get(i).getContent().get(0).get(j)[0] + "")) {
                                //___
                                index++;
                                que.add(index + "_");
                            } else if ("str".equals(list.get(i).getContent().get(0).get(j)[0] + "")) {
                                //有文字
                                que.add(list.get(i).getContent().get(0).get(j)[1] + "");
                            }
                        }
                        questions.add(que);
                    }else {
                        //内容
                        for (int i1 = 0; i1 < list.get(i).getContent().size(); i1++) {
                            ArrayList<String> ques = new ArrayList<String>();
                            for (int j = 0; j < list.get(i).getContent().get(i1).size(); j++) {
                                if ("con".equals(list.get(i).getContent().get(i1).get(j)[0] + "")) {
                                    if (list.get(i).getContent().get(i1).get(j)[1].equals("nl")) {
                                        ques.add("nl");
                                    } else {
                                        ques.add("_");
                                    }
                                } else if ("str".equals(list.get(i).getContent().get(i1).get(j)[0] + "")) {
                                    //有文字
                                    ques.add(list.get(i).getContent().get(i1).get(j)[1] + "");

                                } else if ("img".equals(list.get(i).getContent().get(i1).get(j)[0] + "")) {
                                    ques.add(list.get(i).getContent().get(i1).get(j)[1] + "");
                                }
                            }
                            questions.add(ques);
                        }
                    }

                    b.setContent(questions);
                    //答案前缀
                    for (int j = 0; j < list.get(i).getAnswer().size(); j++) {

                        TIbean.Options op = new TIbean.Options();
                        if ("str".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            op.setOptions(list.get(i).getAnswer().get(j)[0] + "");
                            Log.d("========daan====",list.get(i).getAnswer().get(j)[0] +"");
                            op.setNeirong(list.get(i).getAnswer().get(j)[2] + "");
                            op.setDa(false);
                            answers.add(op);
                        }
                        if ("bool".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            op.setOptions(list.get(i).getAnswer().get(j)[0] + "");
                            op.setNeirong(list.get(i).getAnswer().get(j)[2] + "");
                            op.setDa(false);
                            answers.add(op);
                        }
                        if ("img".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            op.setOptions(list.get(i).getAnswer().get(j)[0] + "");
                            op.setNeirong(list.get(i).getAnswer().get(j)[2] + "");
                            op.setDa(false);
                            answers.add(op);
                        }
                    }
                    b.setOption(answers);
                    //答案内容
                    for (int j = 0; j < list.get(i).getAnswer().size(); j++) {
                        if ("str".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            answerss.add(list.get(i).getAnswer().get(j)[2] + "");
                        }
                        if ("bool".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            answerss.add(list.get(i).getAnswer().get(j)[2] + "");
                        }
                        if ("img".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            answerss.add(list.get(i).getAnswer().get(j)[2] + "");
                        }
                    }

                    //子类题目
                    List<TiXingBean.ListInfo.Child> child = list.get(i).getChild();
                    for (int i1 = 0; i1 < child.size(); i1++) {
                        answers_nei = new ArrayList<String>();//答案内容
                        answers_qian = new ArrayList<TIbean.Options>();//答案前缀
                        TIbean.Clild cl = new TIbean.Clild();
                        //答案内容
                        for (int j = 0; j < child.get(i1).getAnswer().size(); j++) {
                            if ("str".equals(child.get(i1).getAnswer().get(j)[1] + "")) {
                                answers_nei.add(child.get(i1).getAnswer().get(j)[2] + "");
                            }
                        }
                        cl.setAnswers(answers_nei);
                        //答案前缀
                        for (int j = 0; j < child.get(i1).getAnswer().size(); j++) {
                            TIbean.Options op = new TIbean.Options();
                            if ("str".equals(child.get(i1).getAnswer().get(j)[1] + "")) {
                                op.setOptions(child.get(i1).getAnswer().get(j)[0] + "");
                                op.setDa(false);
                                answers_qian.add(op);
                            }
                        }
                        cl.setAnwser_true(child.get(i1).getAnswer_true());
                        cl.setId(child.get(i1).getId());
                        cl.setOption(answers_qian);
                        cc.add(cl);
                    }
                    b.setClild(cc);

                    b.setAnswers(answerss);
                    b.setAnwser_true(list.get(i).getAnswer_true());
                    b.setTitle(list.get(i).getTitle());
                    b.setId(list.get(i).getId());
                    b.setDt_type(list.get(i).getDt_type());
                    b.setQuestion(list.get(i).getQuestion());

                    beanTi.add(b);
                }


                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                if (adapter == null) {
                    adapter = new ZongHeAdapter(ZongHeActivity.this, beanTi);

                    recyclerView.setAdapter(adapter);

                } else {
                    adapter.notifyDataSetChanged();
                }
                try {
                    closeProgressDialog();
                    downLoad(beanList);
                } catch (Exception n) {
                }

            } else if (entity.getEventType() == tiMuPresenter.zuoti_xq_fail) {
                MAlert.alert(entity.getData(), Gravity.TOP);
            }
            //提交答案
            if (entity.getEventType() == tiMuPresenter.tijiao_success) {
                MAlert.alert(entity.getData() + "", Gravity.TOP);
                try {
                    closeProgressDialog();
                    if (player != null) {
                        if (player.isPlaying()) {
                            player.stop();
                        }
                        player.release();
                    }
                } catch (Exception n) {
                }

                YesCuoBean b = new YesCuoBean();

                int dui = 0;
                int cuo = 0;
                int lou = 0;
                if(beanTi.get(0).getDt_type().equals("6227")){
                    for (int i = 0; i < beanTi.get(0).getClild().size(); i++) {
                        if (beanTi.get(0).getClild().get(i).getXuan()== 0) {
                            dui++;
                        }
                        if (beanTi.get(0).getClild().get(i).getXuan() == 1) {
                            cuo++;
                        }
                        if (beanTi.get(0).getClild().get(i).getXuan() == 2) {
                            lou++;
                        }
                    }


                }else{
                    for (int i = 0; i < beanTi.size(); i++) {
                        if (beanTi.get(i).getXuan() == 0) {
                            dui++;
                        }
                        if (beanTi.get(i).getXuan() == 1) {
                            cuo++;
                        }
                        if (beanTi.get(i).getXuan() == 2) {
                            lou++;
                        }
                    }
                }

                b.setCorrect_cnt(dui + "");
                b.setError_cnt(cuo + "");
                b.setMissing_cnt(lou + "");

                if(beanTi.get(0).getDt_type().equals("6227")){
                    List<TiXingBean.ListInfo.Child> child = beanList.get(0).getChild();
                    for (int k=0;k<child.size();k++){
                        TiXingBean.ListInfo.Child child1 = child.get(k);
                        child1.setAnswer_type(beanTi.get(0).getClild().get(k).getXuan()+"");
                    }
                }
                b.setUnit_name(bean.getName());
                List<YesCuoBean.InfoList> info = new ArrayList<>();
                for (int i = 0; i < beanList.size(); i++) {
                    YesCuoBean.InfoList ww = new YesCuoBean.InfoList();
                    ww.setId(beanList.get(i).getId());
                    ww.setTitle(beanList.get(i).getTitle());
                    ww.setNote(beanList.get(i).getNote());
                    ww.setQuestion(beanList.get(i).getQuestion());
                    ww.setCreate_time(beanList.get(i).getCreate_time());
                    ww.setUpdate_time(beanList.get(i).getUpdate_time());
                    ww.setAdded_uid(beanList.get(i).getAdded_uid());
                    ww.setDt_type(beanList.get(i).getDt_type());
                    ww.setAudio_id(beanList.get(i).getAudio_id());
                    ww.setOrigin_article(beanList.get(i).getOrigin_article());
                    ww.setDo_cnt(beanList.get(i).getDo_cnt());
                    ww.setCome_from(beanList.get(i).getCome_from());
                    ww.setKnowledge(beanList.get(i).getKnowledge());
                    ww.setParent_id(beanList.get(i).getParent_id());
                    ww.setStatus(beanList.get(i).getStatus());
                    ww.setContent(beanList.get(i).getContent());
                    ww.setSort(beanList.get(i).getSort());
                    ww.setAudio_path(beanList.get(i).getAudio_path());
                    ww.setAudio_duration(beanList.get(i).getAudio_duration());
                    ww.setAnswer(beanList.get(i).getAnswer());
                    ww.setAnswer_true(beanList.get(i).getAnswer_true());
                    ww.setAnswer_number(beanList.get(i).getAnswer_number());
                    ww.setChild(beanList.get(i).getChild());
                    ww.setAnswer_type(beanTi.get(i).getXuan() + "");
                    info.add(ww);
                }
                b.setList(info);
                Intent intent = new Intent(ZongHeActivity.this, ChengJiActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", b);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }
            if (entity.getEventType() == tiMuPresenter.tijiao_fail) {
                MAlert.alert(entity.getData() + "", Gravity.TOP);
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception n) {
        }
    }
    /**
     * 检测储存卡是否安装
     */
    private boolean mopo() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            file();
            return true;
        } else {
            new AlertDialog.Builder(ZongHeActivity.this).setTitle("提示:")
                    .setMessage("非常抱歉！\n您不能正常使用本软件，可能是以下原因所导致。\n⒈未检测到你手机里的存储卡设备。\n⒉软件经过其他人所修改导致安装文件时出错。\n\n按确定退出本软件！ ").setIcon(R.mipmap.ic_launcher)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            finish();
                        }

                    }).show();
        }

        return false;
    }

    /**
     * 创建文件夹
     */
    private void file() {
        File destDir = new File(ROOT_DIR);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.release();
            player = null;
        }
        if (testTask != null) {
            if (testTask.queue != null) {
                testTask.queue = null;
            }
            testTask = null;
        }
        if (cdt != null) {
            cdt = null;
        }
    }

    //判断文件是否下载完全
    public boolean isFileDownLoadComplete(File file,String url){
        try {
            URL url1=new URL(url);
            URLConnection urlConnection = url1.openConnection();
            int length = urlConnection.getContentLength();
            if(file.exists()&&length == file.length()){
              return true;
            }else {
                return false;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

       return false;
    }
}

